package com.zelma.agent.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zelma.common.utils.PageUtils;
import com.zelma.common.utils.Query;

import com.zelma.agent.dao.HomeFunDao;
import com.zelma.agent.entity.HomeFunEntity;
import com.zelma.agent.service.HomeFunService;


@Service("homeFunService")
public class HomeFunServiceImpl extends ServiceImpl<HomeFunDao, HomeFunEntity> implements HomeFunService {

    @Autowired
    RestHighLevelClient client;
    @Override
    public PageUtils homeFunEslist(Map<String, Object> params) throws IOException {

        SearchRequest searchRequest = new SearchRequest("homeFun");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        String sname = (String) params.get("sname");
        String sprice = (String) params.get("sprice");
        String eprice = (String) params.get("eprice");
        String num = (String) params.get("num");

        if (sname!=null && sname!="") {
            boolQueryBuilder.must(QueryBuilders.matchQuery("home_fun_title",sname));
        }
        if (sprice!=null && sprice!="") {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("price").gte(sprice));
        }
        if (eprice!=null && eprice!="") {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("price").lte(eprice));
        }
        if (num!=null && num!="") {
            boolQueryBuilder.must(QueryBuilders.matchQuery("sum",num));
        }

        searchSourceBuilder.sort("price", SortOrder.DESC);

        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);

        Integer page = Integer.parseInt((String) params.get("page"));
        Integer limit = Integer.parseInt((String) params.get("limit"));

        searchSourceBuilder.from((page-1)*limit);
        searchSourceBuilder.size(limit);

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder.Field highlightTitle =
                new HighlightBuilder.Field("sname");
        highlightTitle.highlighterType("unified");
        highlightTitle.preTags("<b style='color:red'>");
        highlightTitle.postTags("</b>");
        highlightBuilder.field(highlightTitle);
        searchSourceBuilder.highlighter(highlightBuilder);


        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits hits = searchResponse.getHits();

        TotalHits totalHits = hits.getTotalHits();
// the total number of hits, must be interpreted in the context of totalHits.relation
        Long numHits = totalHits.value;
// whether the number of hits is accurate (EQUAL_TO) or a lower bound of the total (GREATER_THAN_OR_EQUAL_TO)
        TotalHits.Relation relation = totalHits.relation;
        float maxScore = hits.getMaxScore();

        SearchHit[] searchHits = hits.getHits();

        ArrayList<HomeFunEntity> list = new ArrayList<>();

        for (SearchHit hit : searchHits) {
            // do something with the SearchHit
            String index = hit.getIndex();
            String id = hit.getId();
            float score = hit.getScore();

            String sourceAsString = hit.getSourceAsString();

            HomeFunEntity  HomeFunEntity = JSON.parseObject(sourceAsString, new TypeReference<HomeFunEntity >() {
            });

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlight = highlightFields.get("home_fun_title");
            if (highlight!=null) {
                Text[] fragments = highlight.fragments();
                String fragmentString = fragments[0].string();
                HomeFunEntity.setHomeFunTitle(fragmentString);
            }
            HomeFunEntity.setHomeFunId(Integer.parseInt(id));
            list.add(HomeFunEntity);
        }
        return new PageUtils(list,numHits.intValue(),limit,page);
    }
}